/*
 * @Author: i@rysa.cn
 * @Date: 2021-04-16 15:25:14
 * @LastEditTime: 2023-09-06 16:48:10
 * @LastEditors: Yietion 549166802@qq.com
 * @Description:
 * @FilePath: \go-utils\DB\db.go
 */

package DB

import (
	"database/sql"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

var (
	db    *gorm.DB
	sqlDb *sql.DB
	err   error
)

type Opt struct {
	Dsn                               string //master
	MaxIdle                           int
	MaxOpen                           int
	LogMode                           logger.LogLevel
	Models                            []any
	DisableForeignKeyCheckWhenMigrate bool
	NamingStrategySingularTable       bool
}

func InitDb(opt *Opt) error {
	var err error
	namingStrategySingularTable := false
	if opt.NamingStrategySingularTable {
		namingStrategySingularTable = true
	}
	db, err = gorm.Open(mysql.Open(opt.Dsn), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: opt.DisableForeignKeyCheckWhenMigrate,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: namingStrategySingularTable,
		},
		Logger: logger.Default.LogMode(opt.LogMode),
		NowFunc: func() time.Time {
			return time.Now().Truncate(time.Millisecond)
		},
	})
	if err != nil {
		return err
	}
	if err := db.AutoMigrate(opt.Models...); err != nil {
		return err
	}
	//连接池设置
	if sqlDb, err = db.DB(); err != nil {
		return err
	} else {
		sqlDb.SetConnMaxIdleTime(time.Hour)
		sqlDb.SetMaxIdleConns(opt.MaxIdle)
		sqlDb.SetMaxOpenConns(opt.MaxOpen)
	}
	return nil
}

func GetDb() *gorm.DB {
	return db
}

func CloseDb() {
	if sqlDb.Ping() != nil {
		return
	}
	_ = sqlDb.Close()
}
